#!/bin/bash
#
# Copyright (C) 2000-2025 Kern Sibbald
# License: BSD 2-Clause; see file LICENSE-FOSS
#
# Simple test for the 'ExlcudedBackupDirectories' FD directive
#
TestName="excluded-backup-dir"
JobName=excluded-dir

. scripts/functions

scripts/cleanup
scripts/copy-confs

echo "${cwd}/build" >${cwd}/tmp/file-list

change_jobname BackupClient1 $JobName
start_test

verify_backup_ok()
{
nb=`grep 'Backup OK' $1 | wc -l`
if [ $nb -lt 1 ]; then
    print_debug "ERROR: should have found Backup OK message, check $1 log"
    bstat=1
fi
}

# Set some directories as excluded
excluded_dir1="$cwd/build/autoconf"
excluded_dir2="$cwd/build/src"
excluded_dirs="${excluded_dir1} ${excluded_dir2}"

# Try to backup and restore 'build' directory respecting the excluded dirs
$bperl -e 'add_attribute("$conf/bacula-fd.conf", "ExlcudedBackupDirectories", "'$excluded_dir1','$excluded_dir2'", "Director")'

# Create directory to compare later
mkdir $tmp/expected
tar -cP $cwd/build | tar -xC $tmp/expected

# Remove excluded directories from expected tree - should not be backed up meaning we do not expect it to be restored
rm -rf $tmp/expected/$cwd/build/autoconf
rm -rf $tmp/expected/$cwd/build/src

cat <<END_OF_DATA >${cwd}/tmp/bconcmds
@$out /dev/null
messages
@$out ${tmp}/log1.out
label volume=TestVolume001 storage=File1 pool=File slot=1 drive=0
run job=$JobName yes
wait
messages
@$out ${tmp}/log2.out
llist files jobid=1
@$out ${tmp}/log3.out
restore where=$tmp/bacula-restores select all done
yes
wait
messages
quit
END_OF_DATA

run_bacula

verify_backup_ok ${tmp}/log1.out

diff -r ${tmp}/expected ${tmp}/bacula-restores
if test $? -ne 0; then
   print_debug "ERROR: Restored tree different than expected one!"
   dstat=1
fi

# Restore 'build' directory - nothing should be backed up now
$bperl -e 'add_attribute("$conf/bacula-fd.conf", "ExlcudedBackupDirectories", "'$cwd/build'", "Director")'

# Restart FD to reload config
$bin/bacula-ctl-fd restart
if test $? -ne 0; then
   print_debug "ERROR: Failed to restart the FD!"
   dstat=1
fi

cat <<END_OF_DATA >${cwd}/tmp/bconcmds
@$out ${tmp}/log4.out
run job=$JobName level=Full yes
wait
messages
quit
END_OF_DATA

run_bconsole

# We should see 'Backup OK' with 0 files written
verify_backup_ok ${tmp}/log4.out

# No files should be written - main backup directory is excluded
n_files=`cat tmp/log4.out | grep 'FD Files Written:' | tr -s ' ' | cut -d ':' -f 2`
if [ ${n_files} -ne 0 ]; then
   estat=1
   print_debug "ERROR: Wrong number of files backed up: ${n_files}, expected: 0, check $tmp/log4.out"
fi


check_for_zombie_jobs storage=File1
stop_bacula

end_test
